package org.example.common.util;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.example.dto.wechat.GetOpenIdInfoParamsDTO;
import org.example.dto.wechat.GetOpenIdInfosResultDTO;
import org.example.enums.BaseErrorEnums;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Component
public class WechatUtils {


    @Value("${wechat.miniapp.appid}")
    private String appId;

    @Value("${wechat.miniapp.secret}")
    private String secret;

    @Autowired
    private RestTemplate restTemplate;


    private final String WEICHAT_API = "https://api.weixin.qq.com";
    // 获取openId
    private final String SESSION_CODE_API = WEICHAT_API + "/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    /**
     * 获取openid
     * @param getOpenIdInfoParamsDTO
     * @return
     */
    public GetOpenIdInfosResultDTO getOpenIdInfo(GetOpenIdInfoParamsDTO getOpenIdInfoParamsDTO){
        log.info("获取openId:{}",getOpenIdInfoParamsDTO);
        String code = getOpenIdInfoParamsDTO.getCode();
        String url = String.format(SESSION_CODE_API,appId, secret,code);
        ResponseEntity<String> forEntity = this.restTemplate.getForEntity(url, String.class);

        String body = forEntity.getBody();
        log.info("返回结果：{}",body);
        GetOpenIdInfosResultDTO result = JSONObject.parseObject(body,GetOpenIdInfosResultDTO.class);
        String errcode = result.getErrcode();
        if (StringUtils.isNotBlank(errcode)){
            ThrowBaseErrorUtils.throwError(BaseErrorEnums.LOGIN_WECHAT_OPENID_ERROR);
        }
        return result;
    }

}
